package com.ophiux.utils.common;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class EncryptUtil {
	public static String Encrypt(String sSrc, String sKey) throws Exception {
		if (sKey == null) {
			System.out.print("Key为空null");
			return null;
		}

		if (sKey.length() != 16) {
			System.out.print("Key长度不是16位");
			return null;
		}
		byte[] raw = sKey.getBytes("utf-8");
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(1, skeySpec);
		byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

		return new Base64().encodeToString(encrypted);
	}

	public static String Decrypt(String sSrc, String sKey) throws Exception {
		try {
			if (sKey == null) {
				System.out.print("Key为空null");
				return null;
			}

			if (sKey.length() != 16) {
				System.out.print("Key长度不是16位");
				return null;
			}
			byte[] raw = sKey.getBytes("utf-8");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(2, skeySpec);
			byte[] encrypted1 = new Base64().decode(sSrc);
			try {
				byte[] original = cipher.doFinal(encrypted1);
				return new String(original, "utf-8");
			} catch (Exception e) {
				System.out.println(e.toString());
				return null;
			}
		} catch (Exception ex) {
			System.out.println(ex.toString());
		}
		return null;
	}

	public static void main(String[] args) throws Exception {
		String text = "rrJS7pFE5lJiKsIwDLUJtc8AJ1ca0FR9mO8feQXWL9/u3Hn7gFLEAzS3Q2uenBAT";
		String token = "A54554B705338651";
		String text1 = Encrypt(text, token);
		System.out.println("密文：" + text1);

		String text2 = Decrypt("rrJS7pFE5lJiKsIwDLUJtc8AJ1ca0FR9mO8feQXWL9/u3Hn7gFLEAzS3Q2uenBAT", token);
		System.out.println("明文：" + text2);
	}
}